package com.treetao.union.web.freemark;

import java.io.IOException;
import java.util.Iterator;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.treetao.union.db.service.SysDictService;

import freemarker.core.Environment;
import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapperBuilder;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateDirectiveModel;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;

@Component
public class FreemarkDirective extends BaseDirective implements TemplateDirectiveModel {

	@Autowired
	private SysDictService dictService;

	private static final String type_dict = "dict";

	private static final String value_list = "list";
	private static final String value_detail = "detail";

	@Override
	public void execute(Environment environment, Map map, TemplateModel[] templateModels,
			TemplateDirectiveBody templateDirectiveBody) throws TemplateException, IOException {
		String type = null;
		String value = null;
		String id = null;
		String group = null;
		Object result = null;

		Iterator iterator = map.entrySet().iterator();
		while (iterator.hasNext()) {
			Map.Entry<String, TemplateModel> param = (Map.Entry<String, TemplateModel>) iterator.next();
			String paramName = param.getKey();
			TemplateModel paramValue = param.getValue();
			if (paramName.toLowerCase().equals("type")) {
				type = getString(paramName, paramValue);
			} else if (paramName.toLowerCase().equals("value")) {
				value = getString(paramName, paramValue);
			} else if (paramName.toLowerCase().equals("id")) {
				id = getString(paramName, paramValue);
			} else if (paramName.toLowerCase().equals("group")) {
				group = getString(paramName, paramValue);
			}
		}

		try {
			if (type_dict.equals(type)) {// 字典
				if (value_list.equals(value)) {
					result = dictService.getDictByType(group);
				} else if (value_detail.equals(value)) {
					result = dictService.getDict(group, id);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		DefaultObjectWrapperBuilder builder = new DefaultObjectWrapperBuilder(Configuration.VERSION_2_3_28);
		environment.setVariable("result", builder.build().wrap(result));
		templateDirectiveBody.render(environment.getOut());
	}

}
